<template>
  <el-dialog
    :title="!dataForm.attrGroupId ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
    @close="close">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
             label-width="80px">
      <el-form-item label="组名" prop="attrGroupName">
        <el-input v-model="dataForm.attrGroupName" placeholder="组名"></el-input>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input-number v-model.number="dataForm.sort" placeholder="排序" :min="0"></el-input-number>
      </el-form-item>
      <el-form-item label="描述" prop="descript">
        <el-input v-model="dataForm.descript" placeholder="描述"></el-input>
      </el-form-item>
      <el-form-item label="组图标" prop="icon">
<!--        <el-input v-model="dataForm.icon" placeholder="组图标"></el-input>-->
        <upload-single-file :fileUrl="dataForm.icon" @update-file="updateLogo"></upload-single-file>
      </el-form-item>
      <el-form-item label="所属分类id" prop="catelogId">
        <!--      <el-input v-model="dataForm.catelogId" placeholder="所属分类id"></el-input>
              v-model="dataForm.catelogId" 就算绑定了，获取到的也还是数组，直接使用事件来获取三级分类
        -->
<!--        <el-cascader @change="categoryChange" :options="categoryTree" :props="defaultProps"
                     v-model="categoryIdArray"
                     placeholder="点击搜索"
                     filterable
                     :show-all-levels="false">
        </el-cascader>-->
<!--        抽取为一个组件之后-->
        <category-tree-cascader @category-change="categoryChangeMethod($event)" :categoryIdArray="categoryIdArray"></category-tree-cascader>

      </el-form-item>


    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
//import categoryApi from '../../../api/categoryApi'
import categoryTreeCascader from '../../common/categoryTreeCascader'
import uploadSingleFile from '../../../../components/upload/uploadSingleFile'

export default {
  name:'attrGroup-add-or-update',
  components:{
    categoryTreeCascader,uploadSingleFile
  },
  data () {
    return {
      visible: false,
      dataForm: {
        attrGroupId: 0,
        attrGroupName: '',
        sort: '',
        descript: '',
        icon: '',
        catelogId: null
      },
      dataRule: {
        attrGroupName: [
          {required: true, message: '组名不能为空', trigger: 'blur'}
        ],
        sort: [
          {required: true, message: '排序不能为空', trigger: 'blur'}
        ],
        descript: [
          {required: true, message: '描述不能为空', trigger: 'blur'}
        ],
        icon: [
          {required: true, message: '组图标不能为空', trigger: 'blur'}
        ],
        catelogId: [
          {required: true, message: '所属分类id不能为空', trigger: 'blur'}
        ]
      },
      defaultProps: {
        label: 'name',
        children: 'children',
        value: 'catId',  // 必须指定value，之后会被作为id，否则报错
        expandTrigger: 'hover'
      },
      categoryTree: [],
      categoryIdArray: []
    }
  },
  methods: {

    init (id) {
      this.dataForm.attrGroupId = id || 0
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.attrGroupId) {
          this.$http({
            url: this.$http.adornUrl(`/pms/attrgroup/info/${this.dataForm.attrGroupId}`),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.dataForm.attrGroupName = data.attrGroup.attrGroupName
              this.dataForm.sort = data.attrGroup.sort
              this.dataForm.descript = data.attrGroup.descript
              this.dataForm.icon = data.attrGroup.icon
              this.dataForm.catelogId = data.attrGroup.catelogId
              /**
               * 三级分类通过后端一并传过来
               * [1141, 123, 16 ,0 ]
               * 1. 需要过滤掉0
               *    [1141, 123, 16 ]
               * 2. 再将数组反转得到
               *    [16, 123, 1141]
               * */
              this.categoryIdArray = data.categoryIdPath.filter(c => {

                return c != 0

              }).reverse()

              console.log('组装好的三级cateGoryId是', this.categoryIdArray)
            }
          })
        }
      })
    },
    // 表单提交
    dataFormSubmit () {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.$http({
            url: this.$http.adornUrl(`/pms/attrgroup/${!this.dataForm.attrGroupId ? 'save' : 'update'}`),
            method: 'post',
            data: this.$http.adornData({
              'attrGroupId': this.dataForm.attrGroupId || undefined,
              'attrGroupName': this.dataForm.attrGroupName,
              'sort': this.dataForm.sort,
              'descript': this.dataForm.descript,
              'icon': this.dataForm.icon,
              'catelogId': this.dataForm.catelogId
            })
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit('refreshDataList')
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        }
      })
    },
    /*getProductCategory () {
          categoryApi.getCategoryTree().then(({data}) => {
            this.categoryTree = data.treeCategoryList.children
          })
        },*/
    categoryChangeMethod (threeLevelCatId) {
      console.log(threeLevelCatId)
      this.dataForm.catelogId = threeLevelCatId[threeLevelCatId.length - 1]
    },
/*    categoryIdArrayUpdate(val){
      this.categoryIdArray = val;
    },*/
    close () {
      /**
       * 关闭对话框的时候清空 categoryIdArray
       * */
      this.categoryIdArray = []
    },
    updateLogo(logo){
      this.dataForm.icon = logo;
    }
  },
  created () {
    //this.getProductCategory()
  }
}
</script>
